<?php
namespace app\mobile\controller;

use app\model\Record; 
use app\model\Util; 
use app\model\Theme; 
use app\model\Worker; 
use app\model\Fans; 
use app\model\Order; 
use app\model\Relation; 

class Yxpay extends Base
{
    public function Yxpay()
    {
global $_G, $_P;
$fans = $this->checkuser();
$system    = $_G['system'];
$op        = !empty($_P['op']) ? $_P['op'] : 'display';
$themeid   = intval($_P['themeid']);
if($themeid < 0){
    return_msg('活动入口不正确');
}
$theme = Theme::getThemeById($themeid);
if(empty($theme['id'])){
    die(Util::showError("请确认活动地址是否正确"));
    return;
}
$config = 	Theme::getConfig($themeid);
$joinid   = intval($_P['joinid']);
$renshu=0;
if ($joinid==4) {
    $joinid = 4;
    $renshu=1;
}
//未支付的进行较验是否已支付
Order::checkorder($themeid,$config,$system);

$recordid   = intval($_P['recordid']);
if (!empty($recordid)) {
    $count = Record::getAttendDetailNumByPId($recordid);
    if ($showrecord['renshu'] == 1) {
        $groupprice = $config['groupprice2'];
        $maxcount = $config['maxcountall2']-1;
        $maxcountall = $config['maxcountall2'];
    }else{
        $groupprice = $config['groupprice'];
        $maxcount = $config['maxcount'];
        $maxcountall = $config['maxcountall'];
    }
    $nowgroupneednum=max(0,$maxcount-$count);
    if ($nowgroupneednum<=0 && $config['tuanmode']==0) {
        $result=  array();
        $result['errcode'] = 1;
        $result['msg'] = "此团已满，无法加入！";
        return_msg($result, '', 'ajax');
    }
}
                    

$type      = $_P['type'];
$forward   = $_P['forward'];
$pm = array(":themeid"=>$themeid);
$p = array(":openid"=>$_G['openid'],":themeid"=>$themeid);

if ($config['wuxian']==0) {
    $pself = $p;
    $pself[':pid'] = $pid;
    $myrecord = db_find ( "SELECT * FROM " . tablename (t_record) . "
                                WHERE themeid =:themeid and pid = :pid
                                        and openid = :openid and status > 0 order by id desc limit 1",$pself);
    if(!empty($myrecord)){
        $result=  array();
        $result['errcode'] = 1;
        $result['msg'] = '每人限购一次';
        return_msg($result, '', 'ajax');
    }  
} 

if($op == 'ready'){
    if ($theme['status']==0 || TIMESTAMP < $theme['begintime']){
        $result=  array();
        $result['errcode'] = 1;
        $result['msg'] = "活动未开始";
        return_msg($result, '', 'ajax');
    }
    if($theme['status']==2){
        $result=  array();
        $result['errcode'] = 1;
        $result['msg'] = "活动已结束";
        return_msg($result, '', 'ajax');
    }
	// $uid = $_G['member']['uid'];
 //    $dbfans = Fans::getByTheme($themeid,$_G['openid']);
	// if($dbfans['status']!=1){
	// 	$result=  array();
	// 	$result['errcode'] = 1;
	// 	$result['msg'] = '请稍后再试';
	// 	return_msg($result, '', 'ajax');
	// }
 //    $workerid = intval($_P['workerid']);
 //    if ($workerid==0){
 //        $relation = Relation::getByThemeId($themeid,$_G['openid']);
 //        $workerid = $relation['workerid'];
 //    }
 //    $fromuid = intval($_P['fromuid']);
	// $fopenid = $_P['fopenid'];
	// if($fromuid == $_G['member']['uid'] || $fopenid == $_G['openid']){
	//     $fromuid = 0;
	//     $fopenid = "";
	// }
	// if($fopenid == "" || $fromuid == 0){
        $isupdaterelation=false;
        $relation = Relation::getByThemeId($themeid,$_G['openid']);
        if(!empty($relation)){
            $fromuid = $relation['parentid'];
            $fopenid = $relation['popenid'];
            $workerid = $relation['workerid'];
        }

        $myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid,1);
        if (empty($myworker)){
            //如果来源为员工,则业绩给员工
            if (!empty($fromuid)){
                $theyworker = Worker::getThemeWorkerByUid($fromuid,$themeid,1);
                if (!empty($theyworker)){
                    $fromuid = $theyworker['uid'];
                    $fopenid = $theyworker['openid'];
                    $workerid = $theyworker['uid'];
                    $isupdaterelation=true;
                }
            }
            //如果来源为空,则给员工
            if (empty($fromuid) && !empty($workerid)){
                $theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);
                $fromuid = $theyworker['uid'];
                $fopenid = $theyworker['openid'];
                $isupdaterelation=true;
            }
            //如果员工为空,则给来源所属员工
            if (!empty($fopenid) && empty($workerid)){
                $theyfrom = Relation::getByThemeId($themeid,$fopenid);
                $workerid = $theyfrom['workerid'];
                $isupdaterelation=true;
            }

            //在没有开启附近团的情况,当团员报名时,员工业绩归属与团长一致
            if ($config['isrecent']==0 && $recordid > 0 && $joinid == 1){
                $record = Record::getAttendGroupById($recordid);
                if (!empty($record['workerid'])){
                    $workerid = $record['workerid'];
                    $isupdaterelation=true;
                }
            }
            if ($isupdaterelation==true){
                    Relation::update($relation['id'],array('parentid' => $fromuid,'popenid' => $fopenid,'workerid' => $workerid));
            }
        }else{
            $fromuid = $_G['member']['uid'];
            $fopenid = $_G['openid'];
            $workerid = $_G['member']['uid'];
        }

    //}
    if (empty($_P['yukuan'])) {
    	$username = $_P['username'];
    	$mobile   = $_P['mobile'];
    	$option   = $_P['option'];
        $jiagetype   = $_P['jiagetype'];
        if ($system['gift']==1) {
           $giftidsvalue  = (array)$_P['address'];

           $giftids = serialize($giftidsvalue);
            $address = "";
            foreach ($giftidsvalue as $index => $id){
                
                $gift = db_find("SELECT * FROM ".tablename(t_gift)." WHERE id = ". $id);
                if (!empty($gift)){
                    if($index != 0){
                        $address.= "|";
                    }
                    $num = $index + 1 ;
                    $address.= $num .".". $gift['giftname'];
                }
            }

        }else{
    	   $address  = $_P['address'];
        }
    	$code     = $_P['code'];
    	$datetime = $_P['datetime'];
    }else{
        $p3 = array(":openid"=>$_G['openid'],":themeid"=>$themeid);
        $recordinfo = db_find ( "SELECT * FROM " . tablename (t_record) . "
                                WHERE themeid =:themeid
                                        and openid = :openid order by id desc limit 1",$p3);
        $username = $recordinfo['username'];
        $mobile   = $recordinfo['mobile'];
        $option   = $recordinfo['option'];
        $address  = $recordinfo['address'];
        $datetime = $recordinfo['datetime'];
    }
    $username=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$username);
    $mobile=preg_replace('#[^0-9]#u','',$mobile);
    $option=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,|，\-]#u','',$option);
    $address=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$address);
    $datetime=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$datetime);


	if(empty($username)){
	    $result['errcode'] = 1;
	    $result['msg'] = '姓名为空';
	    return_msg($result, '', 'ajax');
	}elseif(empty($mobile)){
	    $result['errcode'] = 1;
	    $result['msg'] = '电话为空';
	    return_msg($result, '', 'ajax');
	}elseif(mb_strlen($mobile,"utf-8")!=11){
        $result['errcode'] = 1;
        $result['msg'] = '请输入11位手机号';
        return_msg($result, '', 'ajax');
    }
	if(empty($system['appid']) || empty($system['mchid'] )){
		$result=  array();
		$result['errcode'] = 1;
		$result['msg'] = '支付参数未正确设置';
		return_msg($result, '', 'ajax');
	}
	$fee  = 0;
	$pid  = 0;
    $desclen=26;
    if (!empty($theme['mobile'])){
        $desc = "【客服".$theme['mobile']."】";
        $desclen = $desclen-mb_strlen($desc);
    }
    if (!empty($theme['jubf']) ){
        $desc = mb_substr($theme['jubf'],0,$desclen,"UTF-8").$desc;
    }else{
        $desc = mb_substr($theme['title'],0,$desclen,"UTF-8").$desc;
    }

	if($joinid == 2 && $config['isgoon']==1){//继续开团
        if($config['groupsum'] >0){
            $ktcount = Record::getHasAttendNumByThemeId($themeid);
            if($ktcount >= $config['groupsum']){
                $result=  array();
                $result['errcode'] = 1;
                $result['msg'] = '最大开团数量为'.$config['groupsum'];
                return_msg($result, '', 'ajax');
            }
        }
        $ingrecord = Record::getIngByOpenId($_G['openid'],$themeid);
        if(!empty($ingrecord)){
            $result=  array();
            $result['errcode'] = 110;
            $result['msg'] = '您有正在拼团ing.为您跳转';
            $result['url'] = "/". createMobileUrl('index',array('themeid'=>$themeid,'recordid'=>$ingrecord['id']));
            return_msg($result, '', 'ajax');
        }
        $type = 0;

        if ($config['joinfee']=='0.00'){
            if ($renshu == 1) {
                $fee = floatval($config['groupprice2']);
            }else{
                $fee = floatval($config['groupprice']);
            }
        }else{
            $fee  = floatval($config['joinfee']);
        }
        if ($system['jiage']>0) {
            if ($jiagetype == $config['joinname']) {
                $fee  = floatval($config['joinfee']);
            } elseif ($jiagetype == $config['joinname2']) {
                $fee  = floatval($config['joinfee2']);
            }elseif ($jiagetype == $config['joinname3']) {
                $fee  = floatval($config['joinfee3']);
            }
        }
        
    }else{
        if($joinid == 2){
            $result=  array();
            $result['errcode'] = 1;
            $result['msg'] = '刷新后再重试';
            return_msg($result, '', 'ajax');
        }
	    if($recordid > 0 && $joinid == 1){//团员参团
            $type = 1;

            $record = Record::getPayedGroupById($recordid,$themeid);
            if(empty($record)){
                $result=  array();
                $result['errcode'] = 1;
                $result['msg'] = '没有团长信息 ID：'.$recordid;
                return_msg($result, '', 'ajax');
            }
            // if($record['openid'] == $_G['openid'] ){
            //     $result=  array();
            //     $result['errcode'] = 1;
            //     $result['msg'] = '您是团长 不可以再成为本团团员 ID：'.$recordid;
            //     return_msg($result, '', 'ajax');
            // }

            if ($config['joinfee']=='0.00'){
                if ($record['renshu'] == 1) {
                    $fee = floatval($config['groupprice2']);
                }else{
                    $fee = floatval($config['groupprice']);
                }
            }else{
                $fee  = floatval($config['joinfee']);
            }
            if ($system['jiage']>0) {
                if ($jiagetype == $config['joinname']) {
                    $fee  = floatval($config['joinfee']);
                } elseif ($jiagetype == $config['joinname2']) {
                    $fee  = floatval($config['joinfee2']);
                }elseif ($jiagetype == $config['joinname3']) {
                    $fee  = floatval($config['joinfee3']);
                }
            }
        
            if ($record['renshu'] == 1) {
                $renshu  = 1;
            }

            //$desc = '活动拼团';
            $pr = $pm;
            $pr[':id'] = $recordid;
            $pid = $recordid;

            $count = Record::getAttendDetailNumByPId($recordid);
            $neednum = intval($config['maxcount']);
            if($count >= $neednum && $config['maxcount']==0 ){
                $result=  array();
                $result['errcode'] = 1;
                $result['msg'] = '来晚一步,此团已满!';
                return_msg($result, '', 'ajax');
            }

        }else{//团长开团
            $joinid == 9?$type = 9:$type = 0;
            if ($config['joinfee']=='0.00'){
                if ($joinid == 9){
                    $fee = floatval($config['primeprice']);
                }else{
                    if ($renshu == 1) {
                        $fee = floatval($config['groupprice2']);
                    }else{
                        $fee = floatval($config['groupprice']);
                    }
                }
                
            }else{
                $fee  = floatval($config['joinfee']);
            }
            if ($system['jiage']>0) {
                if ($jiagetype == $config['joinname']) {
                    $fee  = floatval($config['joinfee']);
                } elseif ($jiagetype == $config['joinname2']) {
                    $fee  = floatval($config['joinfee2']);
                }elseif ($jiagetype == $config['joinname3']) {
                    $fee  = floatval($config['joinfee3']);
                }
            }
        
            $myrecord = db_find ( "SELECT * FROM " . tablename (t_record) . "
									WHERE themeid =:themeid
											and openid = :openid and type = 0 and status > 0 order by id desc limit 1",$p);
            // if(!empty($myrecord)){
            //     $result=  array();
            //     $result['errcode'] = 1;
            //     $result['msg'] = '您是团长 不可以再开团啦';
            //     return_msg($result, '', 'ajax');
            // }
            //groupsum
            if($config['groupsum'] >0){
                $ktcount = intval(db_fetchcolumn ( "SELECT COUNT(*) FROM  " . tablename ( t_record ) . "
								WHERE themeid =:themeid and type = 0",$pm));
                if($ktcount >= $config['groupsum']){
                    $result=  array();
                    $result['errcode'] = 1;
                    $result['msg'] = '最大开团数量为'.$config['groupsum'];
                    return_msg($result, '', 'ajax');
                }
            }
        }
    }


    //在线加盟补余款
    if($type == 0 && $system['softstyle']==5){
        $record = db_find ( "SELECT * FROM " . tablename (t_record) . "
                        WHERE themeid =:themeid
                        and openid = :openid and type = 9 and status = 1 order by id desc limit 1",$p);
        if (!empty($record)){
            $fee = $fee - $record['fee'];
        }
        if($fee <=0 ){
            $result=  array();
            $result['errcode'] = 1;
            $result['msg'] = '支付金额不可小于0元';
            return_msg($result, '', 'ajax');
        }
    }
    //补余款
    if ($config['yukuan']>0 && TIMESTAMP>$config['yukuantime']){
        if (empty($_P['yukuan'])) {
            $fee = $config['yukuan'];
        }else{
            $orderpay = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
                WHERE themeid = '{$themeid}' and paystate = 1 and realfee > 0 and uid='{$_G['member']['uid']}'" );
            $fee = sprintf("%.2f",$config['yukuan'] - $orderpay);
            $type = 8;
        }
    }
	if($fee <=0 && $type == 1){
		$result=  array();
		$result['errcode'] = 1;
		$result['msg'] = '参团支付金额不可小于0元';
		return_msg($result, '', 'ajax');
	}
	
	$uncode = $themeid.'-'.TIMESTAMP.rand(1000,1000000);
    if($theme['iskj']==1){

    }else{
        $uncode = $themeid.'-'.TIMESTAMP.rand(1000,1000000);
    }
    
    if($type == 1){//团员参团
        $pself = $p;
        $pself[':pid'] = $pid;
        $myrecord = db_find ( "SELECT * FROM " . tablename (t_record) . "
									WHERE themeid =:themeid and pid = :pid
											and openid = :openid and type = 1 and status > 0 order by id desc limit 1",$pself);
        if(!empty($myrecord)){
            $result=  array();
            $result['errcode'] = 1;
            $result['msg'] = '已经参团啦';
            return_msg($result, '', 'ajax');
        }
        
     //    if($config['istzcy'] == 0){//团长不能参团
     //        $record = db_find ( "SELECT * FROM " . tablename (t_record) . "
					// WHERE themeid = :themeid 
     //                        and type = 0 and openid = :openid and status > 0 order by id desc limit 1",$p);
     //        if(!empty($record)){
     //            $result=  array();
     //            $result['errcode'] = 1;
     //            $result['msg'] = '本次活动团长不能再拼其他团啦';
     //            return_msg($result, '', 'ajax');
     //        }
     //    }
        
     //    if($config['istycy'] == 0){//团员只能参加一次
     //        $sql = "SELECT * FROM " . tablename (t_record) . "
					// WHERE themeid = :themeid  and type = 1 and openid = :openid and status > 0 order by id desc limit 1";
     //        $record = db_find ( $sql,$p);
     //        if(!empty($record)){
     //            $result=  array();
     //            $result['errcode'] = 1;
     //            $result['msg'] = '本次活动只能参加一个团哦';
     //            return_msg($result, '', 'ajax');
     //        }
     //    }
    }else{

    }

    //load_model('mc');
    member_update($_G['member']['uid'],array('mobile' => $mobile,'realname'=>$username));

    //自动更新档案信息
    $data = array(
        'username' => $username,
        'mobile'   => $mobile,
        'address'  => $address,
        'datetime' => $datetime,
        'option'   => $option,
        'jiagetype'   => $jiagetype,
        'fromuid'  => $fromuid,
        'fopenid'  => $fopenid,
        'workerid'  => $workerid,
    );

    if ($system['hdget']==1) {
        if (Fans::getuid_old($fromuid,$themeid)) {
            $data['fromuid_old']  = $fromuid;
            $data['fopenid_old']  = $fopenid;
        }
        if (Fans::getuid_old($workerid,$themeid)) {
            $data['workerid_old']  = $workerid;
        }
    }

    $r = db_update(t_fans,$data,array("uid"=>$_G['member']['uid']));


    $data = array(
        'uniacid'  => $_G['mpid'],
        'themeid'  => $themeid,
        'openid'   => $_G['openid'],
        'uid'	   => $_G['member']['uid'],
        'nickname' => $fans['nickname'],
        'avatar'   => empty($fans['avatar']) ? $fans['headimgurl']:$fans['avatar'],
        'username' => $username,
        'mobile'   => $mobile,
        'addtime'  => TIMESTAMP,
        'fee'      => $fee,
        'address'  => $address,
        'giftids'  => $giftids,        
        'datetime' => $datetime,
        'jiagetype'   => $jiagetype,
        'option'   => $option,
        'code'     => $code,
        'uncode'   => $uncode,
        'status'   => 0,
        'fromuid'  => $fromuid,
        'fopenid'  => $fopenid,
        'workerid'  => $workerid,
        'pid'      => $pid,
        'type'     => $type,
        'renshu'     => $renshu,
    );
    
    if ($system['hdget']==1) {
        if (Fans::getuid_old($fromuid,$themeid)) {
            $data['fromuid_old']  = $fromuid;
            $data['fopenid_old']  = $fopenid;
        }
        if (Fans::getuid_old($workerid,$themeid)) {
            $data['workerid_old']  = $workerid;
        }
    }
    
    $p3 = $p;
    $p3[':type'] = $type;
    $record = db_find ( "SELECT * FROM " . tablename (t_record) . "
									WHERE themeid =:themeid
											and openid = :openid and type = :type and status = 0 order by id desc limit 1",$p3);
        
    $billcode = '';
    if($joinid==2 && $record['status']>0 ){
        $record = null;
    }
    
	if(empty($record)){
        $data['billcode'] = getMillisecond();
        $billcode = $data['billcode'];
	    $r = $insertid = db_insert(t_record,$data);
	    if(!empty($r)){
    	    $recordid = $insertid;
	    }else{
	        $result=  array();
	        $result['errcode'] = 1;
	        $result['msg'] = '请重新下单';
	        return_msg($result, '', 'ajax');
	    }
	    
	    if($system['iswqpay']==1){
    	    $result['errcode'] = 0;
    	    $result['msg'] = 'success';
    	    $result['url'] =   $_G['siteroot'].createMobileUrl('dopay',array('recordid'=>$recordid));
    	    return_msg($result, '', 'ajax');
	    }
	    if (($fee ==0 || $fee=='0.00' )&& $type == 0){
	        $url = $_G['siteroot'].createMobileUrl('index',array('themeid'=>$themeid,'recordid'=>$recordid));
	        if( $system['noticeopen'] == 1){
    	        $message = array(
    	            "url"       =>$url,
    	            "openid"    =>$_G['openid'],
    	            "first"     =>$fans['username'].'您好，您已成功报名'.$djm,
    	            "keyword1"  =>$theme['title'],
    	            "keyword2"  =>$theme['jubf'],
    	            "keyword3"  =>date('Y-m-d',$theme['begintime']).'~'.date('Y-m-d',$theme['endtime']),
    	            "remark"    =>!empty($system['attendok_remark']) ?$system['attendok_remark']:'感谢你的参与，点击查看活动详情,客服电话:'.$theme['mobile'],
    	        );
                Util::sendAttendNotice($message,$system);
	        }
	       if ($system['tixing']==1 && !empty($system['neworder'])) {
                $record = Record::getById($recordid);
                // echo $order['masterid'];
                $worker = Worker::getThemeWorkerByUid($record['workerid'],$themeid,1);
                // var_dump($worker);
                if ($record['type']==9){
                    $orderType='单买';
                }elseif ($record['type']==1){
                    $orderType='团员';
                }elseif (intval($config['maxcountall'])>1) {
                    $orderType='团长';
                }else{
                    $orderType='已支付';
                }

                $paycounttoday = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                        WHERE status > 0 and workerid = '{$record['workerid']}' and addtime>'{$todaytime}' and themeid = '{$themeid}' " );
                $paycount = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                        WHERE status > 0 and workerid = '{$record['workerid']}' and themeid = '{$themeid}' " );
                $message = array(
                    "url"       => $_G['url_scheme'] . DOMAIN0 . '/' .createMobileUrl('w_order',array('themeid'=>$themeid)),
                    "openid"    =>$worker['openid'],
                    "first"     =>'截止' .date('d日H:i分') .', 您今日成交【 ' . $paycounttoday .' 】单, 总计 ' . $paycount .' 单',
                    "tradeDateTime"  => date('Y-m-d H:i:s'),
                    "orderType"  => $orderType,
                    "customerInfo"  => $record['username'] ,
                    "orderItemName"  => '客户电话',
                    "orderItemData"  => $record['mobile'],
                    "remark"    => '微信昵称：'.$record['nickname'],
                );
                // var_dump($message);
                $rec = Util::sendNeworder($message,$system);
                // var_dump($rec);
                // exit;
            }

            Theme::workerreport($themeid,$workerid,array('record' =>1));
            if ($workerid == $fromuid) {
                Theme::workerreport($themeid,$workerid,array('recordzx' =>1));
            }
            if (!empty($fromuid)) {
                db_query("UPDATE ".tablename(t_fans)." SET tuijian = tuijian + 1 WHERE themeid = '{$themeid}' and uid ={$fromuid}");
            }

	        $result['errcode'] = 110;
	        $result['msg'] = '报名成功！';
	        $result['url'] = $url;
	        return_msg($result, '', 'ajax');
	    }
	    
	    
	}else{
        $billcode = $record['billcode'];
	    if($record['status'] == 0){
	        $r = db_update(t_record,$data,array("id"=>$record['id']));
	        if(!empty($r)){
	            $recordid = $record['id'];
	        }else{
	            $result=  array();
	            $result['errcode'] = 1;
	            $result['msg'] = '请重新下单';
	            return_msg($result, '', 'ajax');
	        }
	        if($system['iswqpay']==1){
	            $result['errcode'] = 0;
	            $result['msg'] = 'success';
	            $result['url'] =   $_G['siteroot'].createMobileUrl('dopay',array('recordid'=>$recordid));
	            return_msg($result, '', 'ajax');
	        }
	    }elseif($record['status'] == 1){
	        $result['errcode'] = 1;
	        $result['msg'] = '您已经参团了';
	        return_msg($result, '', 'ajax');
	    }elseif($record['status'] == 2){
	        $result['errcode'] = 1;
	        $result['msg'] = '您已经核销过';
	        return_msg($result, '', 'ajax');
	    }else{
	        $result['errcode'] = 1;
	        $result['msg'] = '请联系管理员';
	        return_msg($result, '', 'ajax');
	    }
	}
	$p[':recordid'] = $recordid;
	$order = db_find ( "SELECT * FROM ".tablename(t_order)."
            WHERE themeid = :themeid and openid = :openid and realfee>0 and masterid=:recordid",$p);
	$data = array(
			'uniacid'  => $_G['mpid'],
			'ordertype'=> $type,
    	    'themeid'  => $themeid,
			'openid'   => $_G['openid'],
			'uid'	    => $_G['member']['uid'],
            'username' => $username,
			'mobile'   => $mobile,
			'status'   => 0,
			'type'     => 'wechat',
	);
    $data['orderfee'] = $fee;
	$data['masterid'] = $recordid;
	$data['detailid'] = $recordid;
    $orderid = 0;
    $tid = '';
	if(empty($order)){
        $module_item = db_get('yx_sys_modules', ['module_name' => MODULE_NAME, 'themeid' => $themeid]);
$module_id = empty($module_item['id']) ? '000000' : sprintf("%06d", $module_item['id']);
$uniontid = date('YmdHis') . $module_id . random(8, 1);
$data['uniontid'] = $uniontid;
$billcode = getMillisecond();
        $tid = '0'.$billcode;
        $data['tid'] = $tid;
        $data['addtime'] = TIMESTAMP;
        $data['ordersn'] = $billcode;
    	$orderid = Order::save($data);
	}elseif($order['paystate'] == 0){
        // $tid = $order['tid'];
        // $orderid = $order['id'];
        // if(TIMESTAMP - $order['addtime'] > 5*60 || $order['orderfee'] != $fee){
            $data['addtime'] = TIMESTAMP;
            $ordersn = getMillisecond();
            $data['ordersn'] = $ordersn;
            $tid = '2'.$ordersn;
            $data['tid'] = $tid;
        // }
        Order::update($order['id'],$data);
	}elseif($order['paystate'] == 1){
	    $result['errcode'] = 1;
	    $result['msg'] = '出错了,请联系管理员';
	    return_msg($result, '', 'ajax');
	}else{
	    $result['errcode'] = 1;
	    $result['msg'] = '请联系管理员';
	    return_msg($result, '', 'ajax');
	}
    $result=  array();
    $result['errcode'] = 0;
    $result['orderid'] =  $orderid;
    $result['tid'] =  $tid;
    $result['fee'] =  $fee;
    $result['title'] =  $desc;
    $result['payway'] = intval($config['payway']);
    $result['url'] =   $_G['siteroot'].createMobileUrl('dopay',array('orderid'=>$orderid));
	return_msg($result, '', 'ajax');

}

// if($op == 'check'){
// 	$orderid = $_P['orderid'];
// 	$torder = db_find ( "SELECT ordersn,themeid FROM " . tablename (t_order) . " WHERE id = '{$orderid}' " );
// 	$checkresult = checkWechatPayByOrderNo($torder['ordersn'],$system);
// 	if($checkresult['errcode'] == 0){
// 		$order = db_find ( "SELECT id,paystate,masterid,themeid,openid,username,ordertype FROM ".tablename(t_order)." 
// 					WHERE  ordersn ='{$torder['ordersn']}'" );
// 		if($order['paystate'] == 0){
// 			$data = array(
// 					'paystate'=>1,
// 					'status'  =>1,
// 					'paytime' =>TIMESTAMP
// 			);
// 			db_update(t_order,$data, array('id' => $order['id']));
// 			$record = db_find ( "SELECT * FROM " . tablename (t_record) . " WHERE  id = :id",array(":id"=>$order['masterid']));
// 			db_update (t_record, array('status'=>1), array ('id'=> $order['masterid']) );
// 			$url = $_G['siteroot'].createMobileUrl('index',array('themeid'=>$order['themeid']));
// 			if($record['type'] == 1){
// 				$p1 = $pm;
// 				$p1[':pid'] = $record['pid'];
// 				$count = intval(db_fetchcolumn ( "SELECT COUNT(*) FROM  " . tablename ( t_record ) . "
// 								WHERE themeid =:themeid and pid = :pid and type = 1 and status > 0 ",$p1));
// 				if($config['maxcount'] > 0 && $count >= $config['maxcount']){
// 					db_update(t_record,array("isfinish"=>1),array("id"=>$record['pid']));
// 				}
// 			}
// 			if($config['iscomm'] == 1 && !empty($record['fopenid']) && $record['fopenid'] != $_G['openid']){

//                 $randomfee = floatval(mt_rand($config['comm11']*100,$config['comm12']*100)/100);
//                 if($record['type'] == 1){
//                     $randomfee = floatval(mt_rand($config['comm1']*100,$config['comm2']*100)/100);
//                 }
// 				$ordersn = getMillisecond();
// 				$data = array(
// 					'uniacid'    => $_G['mpid'],
// 					'themeid'    => $order['themeid'],
// 					'recordid'   => $record['id'],
// 					'ordersn'    => $ordersn,
// 					'type'       => $record['type'],
// 					'openid'     => $record['fopenid'],
// 					'addtime'    => TIMESTAMP,
// 					'fee'        => $randomfee,
// 					'fopenid'    =>$_G['openid'],
// 					'fromuid'    =>$_G['member']['uid'],
// 					'status'     =>0,
// 				);
// 				$insertid = db_insert(t_comm, $data);
// 			}
			
// 			if($system['noticeopen'] == 1){
			    
//     			$message = array(
//     					"url"       =>$url,
//     					"openid"    =>$order['openid'],
//     			        "first"     =>$order['username'].'您好，您已成功报名'.$djm,
//     					"keyword1"  =>$theme['title'],
//     					"keyword2"  =>$theme['jubf'],
//     					"keyword3"  =>date('Y-m-d',$theme['begintime']).'~'.date('Y-m-d',$theme['endtime']),
//     					"remark"    =>!empty($system['attendok_remark']) ?$system['attendok_remark']:'感谢你的参与，点击查看活动详情,客服电话:'.$theme['tel'],
//     			);
//     			$this->sendAttendNotice($message);
// 			}
// 		}
		
// 		$url = "/" . createMobileUrl ( 'index',array('themeid'=>$order['themeid'],'recordid'=>$order['masterid']));
// 		if(!empty($forward)){
// 			$url = base64_decode($forward);
// 		}
// 		$result['errcode']= 0;
// 		$result['msg']= '支付成功';
// 		$result['url']=  $url;
// 	}else{
// 		$result['errcode']= 1;
// 		$result['msg']= $checkresult['errmsg'];
// 	}
// 	return_msg($result, '', 'ajax');
// }










}
}